package com.yoso.core.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yoso.core.exception.BaseException;
import com.yoso.core.enums.CoreException;
import java.util.Map;

/**
 * Jwt工具
 * @link <a href="https://gitee.com/unicorn_dev/java-jwt/tree/3.9.0/"/>
 * @author shizejin
 * @date 2023/12/01 15:02
 */
public class JwtUtil {

    private static final String secret = "secret";
    private static final String issuer = "yoso";

    public static String generate(Map<String, String> claimMap) {
        Assert.notBlank(issuer, () -> new BaseException(CoreException.EMPTY_JWT_ISSUER));
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(issuer);
        if (CollUtil.isNotEmpty(claimMap)) {
            claimMap.forEach(builder::withClaim);
        }
        return builder.sign(algorithm);
    }

    public static DecodedJWT verifier(String token) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(issuer)
                .build();
       return verifier.verify(token);
    }
}
